

class NotificationCenter {
    static NotificationCenter _default = new NotificationCenter();
    var _observerMap = new Map();
    final _segmentKey = '-888-';
    
    /// 发送通知
    /// name 通知名称
    /// param 通知参数
    static void post(String name, [Object param]) {
        if (name != null) {
            NotificationCenter._default._observerMap.forEach((key, value){
                final array = key.split(NotificationCenter._default._segmentKey);
                if (array.length == 2) {
                    final _name = array[0];
                    if (_name == name && value != null) {
                        value(param);
                    }
                }
            });
        }else {
            print('[Notification] post name not null');
        }
    }

    /// 监听通知
    /// observer 监听对象
    /// name 监听的通知名称
    /// block 监听通知的回调
    static void addObserver(Object observer, 
                            String name, 
                            [void block(Object param)]) {
        if(observer != null && name != null) {
            final key = name + NotificationCenter._default._segmentKey + observer.hashCode.toString();
            NotificationCenter._default._observerMap[key] = block;
        }else {
            print('[Notification] observer not null or name not null');
        }
    }


    /// 移除通知
    /// observer 要移除的对象
    /// name 要移除的通知名称（如果为空则移除observer下所有通知）
    static void removeObserver(Object observer, [String name]) {
        if (observer != null) {
            if (name != null) {
                final key = name + NotificationCenter._default._segmentKey + observer.hashCode.toString();
                NotificationCenter._default._observerMap.remove(key);
            }else {
                final keys = NotificationCenter._default._observerMap.keys;
                final List<String> keysToRemove = [];
                
                for (var key in keys) {
                    final array = key.split(NotificationCenter._default._segmentKey);
                    if (array.length == 2) {
                        final hasCode = array[1];
                        if (hasCode == observer.hashCode.toString()) {
                            keysToRemove.add(key);
                        }
                    }
                }
                
                NotificationCenter._default._observerMap.removeWhere((key, value) => keysToRemove.contains(key));
            }
        }
    }
}
